package com.winexpress.account;

import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeTokenRequest;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken;
import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse;
import com.google.api.services.plus.Plus;
import com.winexpress.util.Log;
import com.winexpress.util.SessionAttributes;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.ws.WebServiceRef;

@WebServlet(name = "GoogleCallBack", urlPatterns = {"/googleAuth"})
public class GoogleCallBack extends HttpServlet {
    
    @WebServiceRef(wsdlLocation = "WEB-INF/wsdl/localhost_8080/WineXpress-war/AccountManagementWS.wsdl")
    private AccountManagementWS_Service service;
    
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String code = request.getParameter("code");
        GoogleTokenResponse tokenResponse
                = new GoogleAuthorizationCodeTokenRequest(GoogleSignIn.TRANSPORT, GoogleSignIn.JSON_FACTORY,
                        GoogleSignIn.CLIENT_ID, GoogleSignIn.CLIENT_SECRET, code, "https://localhost:8181/WineXpressClient/googleAuth").execute();
        GoogleIdToken idToken = tokenResponse.parseIdToken();
        String gplusId = idToken.getPayload().getSubject();
        String email = idToken.getPayload().getEmail();
        Customer customer = getGoogleCustomerAccount(gplusId, email, "", email);
        HttpSession session = request.getSession();
        if ((customer == null) || !customer.isActivated()) {
            session.setAttribute(SessionAttributes.ACCOUNT_DEACTIVATED, true);
            response.sendRedirect("/WineXpressClient/loginFail.jsp");
            return;
        }
        session.setAttribute(SessionAttributes.GOOGLE_TOKEN, tokenResponse.toString());
        session.setAttribute(SessionAttributes.USER_ID, customer.getId().toString());
        session.setAttribute(SessionAttributes.IS_ADMIN, false);
        session.setAttribute(SessionAttributes.USER_FIRST_NAME, customer.getFirstName());
        session.setAttribute(SessionAttributes.USER_EMAIL, customer.getEmail());
        Log.info("Google user = " + SessionAttributes.USER_ID + " Log in");
        response.sendRedirect(request.getContextPath() + "/initialization/index");
    }

// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    private Customer getGoogleCustomerAccount(java.lang.String googleId, java.lang.String firstName, java.lang.String lastName, java.lang.String email) {
        com.winexpress.account.AccountManagementWS port = service.getAccountManagementWSPort();
        try {
            Customer googleUser = new Customer();
            googleUser.setGooogleID(googleId);
            googleUser.setFirstName(firstName);
            googleUser.setLastName(lastName);
            googleUser.setEmail(email);
            return port.getGoogleCustomerAccount(googleUser);
        } catch (Exception_Exception ex) {
            Logger.getLogger(GoogleCallBack.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }
    
}
